#include "stdafx.h"
#include <time.h>
#include <stdio.h>
#include <iostream>
#include <stdarg.h>
#include <windows.h>
#include "log_ctl.h"

#define LOG_FILE_PREFIX "rec"
#define MAX_LEN_WR_ONCE 256

CLogFile * g_logCtl = NULL;

CLogFile::CLogFile()
{
    time_t t = time(0);
    char tmp[64];
    char fileName[128];

    tm stTime;
    
    localtime_s(&stTime,&t);

    strftime(tmp, sizeof(tmp), "%Y_%m_%d_%H_%M", &stTime);
    
    sprintf_s(fileName,"%s_%s.log",LOG_FILE_PREFIX,tmp);

    printf("log file is:%s\r\n",fileName);

	fpLogFile = _fsopen(fileName, "wb+", _SH_DENYWR);

    mutex_wr = CreateMutex(NULL,FALSE,NULL);    
}

CLogFile::~CLogFile()
{
    if(fpLogFile)
    {
        fclose(fpLogFile);
        fpLogFile = NULL;
    }
    
    CloseHandle(mutex_wr);
}

void CLogFile::info(const char * format, ...)
{
    if(fpLogFile == NULL)
    {
        return;
    }

    va_list ap;
    WaitForSingleObject(mutex_wr,5000);
    
    va_start(ap,format);

    char strInfo[MAX_LEN_WR_ONCE];

    vsnprintf_s(strInfo,MAX_LEN_WR_ONCE, format, ap);

    char strToWrite[MAX_LEN_WR_ONCE];

    time_t t = time(0);

    char tmp[64];
    
    tm stTime;

    localtime_s(&stTime,&t);

    //strftime(tmp, sizeof(tmp), "%T", &stTime);
	sprintf_s(tmp, "%02d:%02d:%02d", stTime.tm_hour, stTime.tm_min, stTime.tm_sec);
    
    sprintf_s(strToWrite,"%s %s",tmp,strInfo);

    fputs(strToWrite,fpLogFile);

    fflush(fpLogFile);

    va_end(ap);
    
    ReleaseMutex(mutex_wr);
}


void CLogFile::init(void)
{
	if (g_logCtl)
	{
		delete g_logCtl;
	}
	CLogFile * g_logCtl = new CLogFile();
}

